frappe.ui.form.on('Sales Order', {
    refresh(frm){
        zelin_shoe_biz.utils.change_grid_col_label(frm);
    },
    size_range(frm) {
        zelin_shoe_biz.utils.change_grid_col_label(frm);
    },
    get_items_fields_from_mapping_table(frm){},
    // Optional: If you want to ensure popup labels are updated immediately upon opening
    // This is more of a fallback/additional measure if reset_grid doesn't fully cover it.
    items_on_form_render: function(frm, cdt, cdn) {
        // This function is called when a child row's form is rendered (popup opens)
        let row_doc = frappe.get_doc(cdt, cdn);
        if (frm.doc.size_range) {
            frappe.db.get_doc('Size Range', frm.doc.size_range).then(size_range_doc => {
                for (let j = 1; j <= 20; j++) {
                    let size_field_name = `size_${j}`;
                    let qty_field_name = `qty_${j}`;
                    let new_label = size_range_doc[size_field_name] || `Qty ${j}`;

                    // Update the field label in the child form (popup)
                    let field = cur_frm.get_field(qty_field_name, cdn); // cur_frm refers to the child table form context
                    if (field) {
                        field.set_label(new_label);
                    }
                }
            });
        }
    },
    items_batch_copy(frm, child_rows) {
	    frappe.call({
			method: "zelin_shoe_biz.api.batch_copy_items",
			args: {
			    doc: frm.doc,
			    child_rows: child_rows
			},
			freeze: true,
			freeze_message: __("后台处理中 ..."),
		})
		.then(r =>{
		    frappe.model.sync(r.message);
		    frm.refresh();
		})
	}
});

